package com.dfrz.planeclub.interceptor;

import com.alibaba.fastjson.JSON;

import com.dfrz.planeclub.utill.BaseResult;
import com.dfrz.planeclub.utill.ResultCodeEnum;
import com.dfrz.planeclub.utill.StringUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author PuXiaLing
 * @description: TODO
 * @date 2024/3/27 22:29
 */
public class AuthorityInterceptor implements HandlerInterceptor {

    @Resource
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       String mytoken=request.getHeader("mytoken");
        if (StringUtil.isNotEmpty(mytoken)){
            Integer uid= (Integer) redisTemplate.opsForValue().get(mytoken);
            if (uid!=null){
                return true;
            }
        }
        //如果没有传token，返回前端错误信息
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pw = response.getWriter();
        BaseResult baseResult = BaseResult.setResult(ResultCodeEnum.PARAM_ERROR, null);
        pw.print(JSON.toJSONString(baseResult));
        return false;
    }

}
